package com.zpark.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.zpark.pojo.User;
import com.zpark.util.ResultJsonUtil;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.zpark.controller
 * @ClassName: UserController
 * @Description:
 * @author: RZS
 * @date: 2024/4/17  11:39
 */
@RestController
@RequestMapping("/user")
public class UserController {

    // 伪造数据
    List<User> lists = new ArrayList<>();

    public UserController(){
        lists.add(new User(1, "大锤", "123456"));
        lists.add(new User(2, "张三", "123456"));
        lists.add(new User(3, "李四", "123456"));
        lists.add(new User(4, "王五", "123456"));
        lists.add(new User(5, "赵六", "123456"));
        lists.add(new User(6, "钱七", "123456"));
        lists.add(new User(7, "锤锤", "123456"));
    }

    @GetMapping("/all")
    @HystrixCommand(fallbackMethod = "hystrixMethod")
    public ResultJsonUtil<List<User>> getAll(){
        int num = 1 / 0;
        return new ResultJsonUtil<>(2000, "SUCCESS", lists);
    }

    @GetMapping("/test")
    public ResultJsonUtil<Void> test(){
        throw new RuntimeException("手动抛出异常");
    }

    /**
     * hystrixMethod方法的参数要跟注解的方法参数保持一致，否则会报错。
     * 而且两个方法必须要在同一个类中，由于在同一个类中，
     * 所以hystrixMethod的修饰符没有限制
     * @return
     */
    private ResultJsonUtil<List<User>> hystrixMethod(){
        return new ResultJsonUtil<>(5000,
                "服务器内部错误", null);
    }

    @GetMapping("/hello/{id}")
    @HystrixCommand(fallbackMethod = "hystrixTest")
    public String callHole(@PathVariable Integer id){
        /**
         * 调用服务代码略
         * 这里只为显示效果
         */
        if(id == 1){
            throw new RuntimeException("服务调用失败...");
        }
        return "调用成功";
    }

    private String hystrixTest(@PathVariable Integer id){
        return "服务器繁忙，请稍后再试！！！";
    }
}
